import dayjs from 'dayjs';

export default {
  data() {
    return {
      formData: {
        dateRange: [

        ],
        couponName: '',
      },
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      dialogData: null,
      tableData: [],
      showDialog: false,

      dateFormat: {
        format1: 'YYYYMMDDHHmmss',
        format2: 'YYYY-MM-DD HH:mm:ss',
      },
    };
  },
  mounted() {
    this.getCouponList();
  },
  methods: {
    doSearch() {
      this.pagination.pageNum = 1;
      this.getCouponList();
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.getCouponList();
    },
    handleCurrentChange(num) {
      this.pagination.pageNum = num;
      this.getCouponList();
    },
    viewDetail(show = true, data, refresh = false) {
      this.showDialog = show;
      this.dialogData = data;
      refresh && this.getCouponList();
    },
    async getCouponList() {
      const { couponName, dateRange = [] } = this.formData;
      const { pageNum, pageSize } = this.$data.pagination;

      let validStart;
      let validEnd;

      if (dateRange && dateRange.length) {
        validStart = dayjs(dateRange[0]).format('YYYYMMDDHHmmss');
        validEnd = dayjs(dateRange[1]).format('YYYYMMDDHHmmss');
      }
      const params = { couponName, validStart, validEnd, pageNum, pageSize };
      if (params.validStart === undefined) delete params.validStart;
      if (params.validEnd === undefined) delete params.validEnd;
      const { success, data, total } = await this.$api.getCouponList(params);
      // console.log(total, 'total')
      if (success) {
        this.tableData = data.map(item => {
          item.createTime = dayjs(item.createTime).format(
            'YYYY-MM-DD HH:mm:ss'
          );
          return item;
        });
        this.pagination.total = total;
      }
    },
    dialogClose(refresh = false) {
      this.showDialog = false;
      refresh && this.getCouponList();
    },
    async manageCoupon(type, { id }) {
      // delete
      if (type === 3) {
        this.$confirm('确定要删除该优惠券吗, 此操作无法恢复', '警告')
          .then(async() => {
            const { success } = await this.$api.manageCoupon(id, type);
            success &&
              (this.getCouponList(), this.$message.success('删除成功'));
          })
          .catch(() => {});
      } else {
        const { success } = await this.$api.manageCoupon(id, type);
        success && this.getCouponList();
      }
    },
  },
};
